var util = require('../../../utils/util.js');
var apiObject = require('../../../utils/api.js');
var app = getApp();

Page({

  data: {
    elementCheckedList:[],
    monitorPlan:{title:"",describe:""}
  },
  onLoad: function () {
    var that=this;
    util.request(apiObject.api.getPlanById).then(function (res) {
      console.log(res)
      if (res.code == 200) {
        that.setData({
          elementCheckedList: res.result.elementCheckedList
        })
        wx.setStorageSync("plan", res.result.elementCheckedList)
      } else {
        util.showModal(res.message);
      }
    })

  },
  onShow: function (e) {
    var that=this;
    var plan=wx.getStorageSync("plan")
    that.setData({
      elementCheckedList: plan,
    })
  },



  titleInput: function (e) {
    var title ="monitorPlan.title"
    this.setData({
      [title]: e.detail.value
    })
  },
  describeInput: function (e) {
    var describe = "monitorPlan.describe"
    this.setData({
      [describe]: e.detail.value
    })
  },

  chooseElement:function(e){
    var index = e.currentTarget.dataset.index;
    var plan=wx.getStorageSync("plan");
    plan[index].checked = !this.data.elementCheckedList[index].checked
    wx.setStorageSync("plan",plan);
    console.log(plan)
    this.setData({
      elementCheckedList: plan
    })
  },
  redirectToPlanDetail:function(e){
    var index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: `../setPlanElement/index?index=${index}` ,
    })
  },
  submit:function(){
    if (this.data.monitorPlan.title.trim()==""){
      util.showModal("方案名称不能为空");
      return;
    }
    if (this.data.monitorPlan.describe.trim() == "") {
      util.showModal("方案描述不能为空");
      return;
    }

    console.log(this.data)
    var data = {
      id: this.data.monitorPlan.id,
      title:this.data.monitorPlan.title,
      describe: this.data.monitorPlan.describe,
      elementChecked:[]
    }
    for (var index in this.data.elementCheckedList) {
      var item = this.data.elementCheckedList[index];
      data.elementChecked.push({ min: item.min, max: item.max, value: item.value, id: item.id, checked: item.checked, equipmentCategory:item.equipmentCategory})
    }
    console.log(data)
    util.request(apiObject.api.savePlan, data, "application/json").then(function (res) {
      console.log(res)
      if (res.code == 200) {
        util.showModal("保存成功").then(function (res) {
          wx.navigateBack()
        })
      } else {
        util.showModal(res.message);
      }
    })


  }
})